///////////////////////////////////////////////////////////////////////////
//
// Spring Engine Source File.
// Copyright (C), Dengtao 2011-2021
// ----------------------------------------------------------------------
// File name:   SfMemoryAllocManager.h
// Version:     v1.0.0
// Created:     2013/06/13 23:22 by dengtao
// Compilers:   Visual Studio 2008
// Description: 
// ----------------------------------------------------------------------
// History:
//
///////////////////////////////////////////////////////////////////////////

#include "SfBaseDefines.h"
#include "SfSharedSingleton.h"
#include "SfMemoryAllocator.h"
#include "SfDefaultMemoryAllocator.h"
#include "SfMemoryTracker.h"
#include "SfDefaultMemoryTracker.h"
#include "SfDelegate.h"
#include <stdlib.h>

namespace Sunflower
{

//////////////////////////////////////////////////////////////////////////
//Summary:
//	
//////////////////////////////////////////////////////////////////////////
class MemoryAllocManager : public SharedSingleton<MemoryAllocManager>
{
public:
	//
	//Summary:
	//	Default constructor.
	MemoryAllocManager();

	//
	//Summary:
	//	virtual destructor.
	virtual ~MemoryAllocManager();

	//
	//Summary:
	//	Allocate a block from MemoryAllocManager.
	virtual void* Alloc(size_t size);
	virtual void* Alloc(size_t size, const char* file, int line, 
		const char* func);

	//
	//Summary:
	//	Free a object from MemoryAllocManager.
	virtual bool Free(void* p);
	virtual bool Free(void* p, const char* file, int line, 
		const char* func);

	//
	//Summary:
	//	raise event_MemroyWarning.
	void RaiseMemoryWarning(size_t requestSize);

	//
	//Summary:
	//	set allocator.
	void SetAllocator(MemoryAllocator* allocator);
	MemoryAllocator* GetAllocator();
	const MemoryAllocator* GetAllocator() const;

	//
	//Summary:
	//	memory tracker
	void SetTracker(MemoryTracker* trakcer);
	MemoryTracker* GetTracker();
	const MemoryTracker* GetTracker() const;

public:
	//
	//Summary:
	//	event MemoryWarning
	typedef EventHandler<void (MemoryAllocManager*, size_t)> 
		EventMemoryWarning;
	EventMemoryWarning evnet_MemoryWarning;

protected:
	//
	//Summary:
	//	callback when alloc failed once.
	virtual void OnMemoryWarning(size_t requestSize);

	//
	//Summary:
	//    MemAlloc 
	void* MemAlloc(size_t size);
	
	//
	//Summary:
	//	MemFree
	bool MemFree(void* p);

protected:
	MemoryAllocManager(const MemoryAllocManager&);
	MemoryAllocManager& operator =(const MemoryAllocManager&);

private:
	MemoryAllocator* m_Allocator;
	MemoryTracker* m_Tracker;
	DefaultMemoryAllocator m_DefaultAllocator;
};

#include "SfMemoryAllocManager.inl"

} // end of namespace Sunflower
